<?php

namespace app\admin\controller\coupon;

use app\common\controller\Backend;

/**
 * 优惠券管理
 *
 * @icon fa fa-circle-o
 */
class Coupon extends Backend
{
    protected $relationSearch = true;

    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Coupon.Coupon');
        $this->view->assign("statusList", $this->model->statuslist());
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);

        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count();  //查询总数

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();  //查询数据

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) 
        {
            $params = $this->request->post('row/a');

            if ($params) 
            {
                $params['endtime'] = strtotime($params['endtime']);
                $result = $this->model->validate("common/Coupon/Coupon")->save($params);

                if ($result === false) 
                {
                    $this->error($this->model->getError());
                    exit;
                }

                $this->success();
                exit;
            }
        }

        $this->assign('statuslist', build_select('row[status]', $this->model->statuslist(), [], ['class'=>'selectpicker', 'required'=>'']));

        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->find($ids);

        if (!$row) 
        {
            $this->error(__('未找到当前来源名称'));
            exit;
        }

        if ($this->request->isPost()) 
        {
            $params = $this->request->post("row/a");

            if ($params) 
            {
                $params['id'] = $ids;
                $params['endtime'] = strtotime($params['endtime']);
                
                $result = $this->model->validate("common/Coupon/Coupon")->isUpdate(true)->save($params);

                if ($result === false) 
                {
                    $this->error($this->model->getError());
                    exit;
                }

                // 如果图片名称不一样时说明有更新图片，需要把旧图片删除
                if($params['thumb'] != $row['thumb'])
                {
                    $thumb = ltrim($row['thumb'],'/');
                    @is_file('.'.$row['thumb']) && @unlink('.'.$row['thumb']);
                }

                $this->success();
                exit;
            }
        }

        $this->assign('statuslist', build_select('row[status]', $this->model->statuslist(), $row['status'], ['class'=>'selectpicker', 'required'=>'']));

        $this->assign("row", $row);

        return $this->view->fetch();
    }

    public function del($ids = null)
    {
        $ids = !empty($ids) ?  explode(',', $ids) : [];

        $row = $this->model->select($ids);

        if(!$row)
        {
            $this->error(__('No results were found'));
            exit;
        }

        $result = $this->model->destroy($ids);

        if ($result === false) 
        {
            $this->error($this->model->getError());
            exit;
        }


        $thumb = array_column($row, "thumb");
        $thumb = array_filter($thumb);
        $thumb = array_unique($thumb);

        if(!empty($thumb))
        {
            foreach($thumb as $item)
            {
                $item = ltrim($item,'/');
                @is_file($item) && @unlink($item);
            }
        }

        $this->success();
        exit;

    }
    
    //领取记录
    public function receive($ids = null)
    {
        $this->model = model('Coupon.Receive');

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isAjax()) 
        {
            if ($this->request->request('keyField')) 
            {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $DataWhere = ['cid' => $ids];

            $total = $this->model
                ->with(['business'])
                ->where($where)
                ->where($DataWhere)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count();

            $list = $this->model
                ->with(['business'])
                ->where($where)
                ->where($DataWhere)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }


}
